#include <QDebug>
#include <QVBoxLayout>
#include <QListWidget>

#include "imageswindow.h"
#include "../tukupageparser.h"
#include "../imagepageparser.h"

namespace Jcr
{
class ImagesWindowPrivate
{
public:
    ImagesWindowPrivate(ImagesWindow* q);

    ImagesWindow* q_ptr;
    QStringList imageLinks;
    QListWidget* listWidget;
};

ImagesWindowPrivate::ImagesWindowPrivate(ImagesWindow *q) : q_ptr(q)
{

}

ImagesWindow::ImagesWindow(QWidget* parent) : ModelWindow(parent)
{
    d_ptr = new ImagesWindowPrivate(this);
    d_ptr->listWidget = new QListWidget(this);
    d_ptr->listWidget->setAlternatingRowColors(true);
    QVBoxLayout* layout = new QVBoxLayout;
    layout->setContentsMargins(0, 0, 0, 0);
    layout->addWidget(d_ptr->listWidget);
    setLayout(layout);
}

ImagesWindow::~ImagesWindow()
{
    delete d_ptr;
}

void ImagesWindow::exec()
{
    d_ptr->listWidget->clear();
    foreach (auto link, d_ptr->imageLinks) {
        Jcr::TukuPageParser* tpp = new Jcr::TukuPageParser;
        tpp->setUrl(QUrl(link));
        tpp->setModelName(this->modelName());
        tpp->setBrandName(this->brandName());
        connect(tpp, SIGNAL(getImageUrl(QUrl)), this, SLOT(onGetRedirectUrl(QUrl)));
        tpp->run();
    }
}

void ImagesWindow::setLinks(const QStringList &links)
{
    if (d_ptr->imageLinks != links)
        d_ptr->imageLinks = links;
}

void ImagesWindow::clear()
{
    d_ptr->listWidget->clear();
}

void ImagesWindow::onGetRedirectUrl(const QUrl &url)
{
    qDebug() << "[Tuku url]: " << url;
    Jcr::TukuPageParser* tpp = qobject_cast<Jcr::TukuPageParser*>(sender());
    tpp->deleteLater();

    Jcr::ImagePageParser* ipp = new Jcr::ImagePageParser;
    connect(ipp, SIGNAL(finished()), this, SLOT(onFinishedParseImages()));
    connect(ipp, SIGNAL(finishedSavingImages()), this, SIGNAL(finished()));
    ipp->setModelName(modelName());
    ipp->setBrandName(brandName());
    ipp->setUrl(url);
    ipp->run();
}

void ImagesWindow::onFinishedParseImages()
{
    Jcr::ImagePageParser* ipp = qobject_cast<Jcr::ImagePageParser*>(sender());
    const QStringList imgs = ipp->images();
    foreach (auto img, imgs) {
        QListWidgetItem* item = new QListWidgetItem;
        item->setText(img);
        d_ptr->listWidget->addItem(item);
    }

    ipp->deleteLater();
}

} // namespace jcr
